package leetcode_401_500;

import node.ListNode;

public class LeeCode_445 {
    public static void main(String[] args) {
        System.out.println(addTwoNumbers(new ListNode(7, new ListNode(2, new ListNode(4, new ListNode(3)))),
                new ListNode(5, new ListNode(6, new ListNode(4)))));
    }
    private static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuilder s1 = new StringBuilder();
        while (l1 != null){
            s1.append(l1.val);
            l1 = l1.next;
        }
        StringBuilder s2 = new StringBuilder();
        while (l2 != null){
            s2.append(l2.val);
            l2 = l2.next;
        }
        StringBuilder res = new StringBuilder();
        s1.reverse();
        s2.reverse();
        int t = 0, i = 0;
        while (i < s1.length() || i < s2.length()){
            int n1 = i < s1.length() ? s1.charAt(i) - '0' : 0;
            int n2 = i < s2.length() ? s2.charAt(i) - '0' : 0;
            int sum = n1 + n2 + t;
            res.append(sum % 10);
            t = sum / 10;
            i++;
        }
        res.append(t > 0 ? t : "");
        res.reverse();
        ListNode ans = new ListNode(0);
        ListNode cur = ans;
        for (int j = 0; j < res.length(); j++) {
            cur.next = new ListNode(res.charAt(j) - '0');
            cur = cur.next;
        }
        return ans.next;
    }
}
